package com.springboot_shopping.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot_shopping.entity.Order;
import com.springboot_shopping.entity.OrderItem;
import com.springboot_shopping.entity.User;
import com.springboot_shopping.entity.UserAddress;
import com.springboot_shopping.service.OrderItemService;
import com.springboot_shopping.service.OrderService;
import com.springboot_shopping.service.UserAddressService;
import com.springboot_shopping.service.UserService;
import com.springboot_shopping.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private OrderItemService orderItemService;


    // 获取当前用户的订单列表
    @GetMapping("/list")
    public Result<List<Order>> list(HttpSession session, HttpServletRequest request) {
        String userId = request.getHeader("userId");
        if (userId == null) {
            return Result.error("未登录");
        }
        // 查询订单及商品明细
        List<Order> orderList = orderService.findOrdersWithItemsAndProducts(Integer.valueOf(userId));
        return Result.success(orderList);
    }

    // 创建订单
    @PostMapping("/create")
    public Result<Order> create(@RequestBody Order order,
                                @RequestParam("cartItemIds") List<Integer> cartItemIds,
                                @RequestParam("addressId") Integer addressId,
                                HttpSession session,
                                HttpServletRequest request) {
        User user = (User) session.getAttribute("user");
        String userId = request.getHeader("userId");
        if (userId == null) {
            return Result.error("未登录");
        }

        // 设置订单用户ID
        order.setUserId(Integer.valueOf(userId));

        // 获取地址信息并设置订单收货信息
        UserAddress address = userAddressService.findById(addressId);
        if (address == null) {
            return Result.error("地址不存在");
        }
        order.setAddress(address.getAddress());
        order.setConsignee(address.getConsignee());
        order.setPhone(address.getPhone());

        // 创建订单
        boolean success = orderService.createOrder(order, cartItemIds, addressId);
        if (success) {
            // 返回创建好的订单（包含订单号等信息）
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getUserId, Integer.valueOf(userId));
            wrapper.orderByDesc(Order::getCreateTime);
            wrapper.last("LIMIT 1");
            Order newOrder = orderService.getOne(wrapper);
            return Result.success(newOrder);
        } else {
            return Result.error("创建订单失败");
        }
    }

    // 删除订单
    @DeleteMapping("/{orderId}")
    public Result<String> delete(@PathVariable Integer orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }

        // 验证订单是否属于当前用户
        Order order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(user.getUserId())) {
            return Result.error("订单不存在或无权限删除");
        }

        boolean success = orderService.deleteOrder(orderId);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    // 搜索订单
    @GetMapping("/search")
    public Result<List<Order>> search(@RequestParam("keyword") String keyword, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }
        List<Order> orderList = orderService.searchOrders(keyword, user.getUserId());
        return Result.success(orderList);
    }

    // 获取订单详情（包含订单明细）
    @GetMapping("/{orderId}")
    public Result<Order> detail(@PathVariable Integer orderId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("未登录");
        }

        Order order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(user.getUserId())) {
            return Result.error("订单不存在或无权限查看");
        }

        // 查询订单明细，使用OrderItemService查询
        List<OrderItem> orderItems = orderItemService.findByOrderId(orderId);
        order.setOrderItems(orderItems);

        return Result.success(order);
    }
}